import { createPinia } from 'pinia'
import { defineStore } from 'pinia'
import api from '@/api/index.js'

// 创建 Pinia 实例
export const pinia = createPinia()

// 用户状态管理
export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    isLoggedIn: false,
    token: null
  }),

  getters: {
    // 是否已登录
    hasLogin: (state) => state.isLoggedIn && state.token,
    // 用户昵称
    nickname: (state) => state.userInfo?.nickname || '未登录',
    // 用户头像
    avatar: (state) => state.userInfo?.avatar || '/static/touxiang.png'
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      this.isLoggedIn = true
      uni.setStorageSync('userInfo', userInfo)
    },

    // 设置token
    setToken(token) {
      this.token = token
      uni.setStorageSync('token', token)
    },

    // 微信登录
    async wechatLogin() {
      try {
        // 获取微信登录code
        const loginRes = await new Promise((resolve, reject) => {
          uni.login({
            provider: 'weixin',
            success: resolve,
            fail: reject
          })
        })
        if (loginRes.code) {
          const response = await api.login({ code: loginRes.code })
          
          if (response.code === 1) {
            const { userinfo } = response.data
            this.setUserInfo(userinfo)
            this.setToken(userinfo.token)
            return { success: true }
          }
        }
        return { success: false }
      } catch (error) {
        return { success: false }
      }
    },

    // 登出
    logout() {
      this.userInfo = null
      this.isLoggedIn = false
      this.token = null
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('token')
    },

    // 初始化用户状态
    initUserState() {
      const userInfo = uni.getStorageSync('userInfo')
      const token = uni.getStorageSync('token')
      
      if (userInfo && token) {
        this.setUserInfo(userInfo)
        this.setToken(token)
      }
    }
  }
})

export default pinia
